<template>
  <div class="merak-container-has-aside" curPageName="67tttttryab">
    <div class="merak-aside">
      <treeNode curPageName="1710501880167" :defTreeValue="treeNodeDefaultOrgId" @node-change="treeNodeChange"></treeNode>
    </div>
 
    <div v-waterMarker="{zIndex: 10}" class="merak-card merak-table-wrapper merak-container-has-search" curPageName="67ab">
      <searchBar
        ref="searchbar"
        :placeholder="$t(`contract_signed.enter_job_number_or_name`)"
        searchName="employee_name_job_no"
        @search-event="searchBarPost"
        v-model="searchform"
        plan-key="key"
        curpagename="s55787e5352"
      >
        <template #footer>
          <!-- <el-button type="primary">新增合同记录</el-button> -->
        </template>
        <!-- 高级搜索弹出框 插槽-->
        <template #searchForm="searchProp">
          <!--  高级搜索弹出框内容-->
          <div class="modal-content">
            <!-- 高级搜索 -->
            <div class="modal-title">
              <!-- {{ $t(`merak.search_list_ad`) }} -->
            </div>

            <div class="modal—body">
              <el-scrollbar height="100%">
                <div class="scrollbar-content">
                  <!-- 已选参数 组件-->
                  <selectedParams v-model="searchform" label="label" val="value" option-key="options"></selectedParams>

                  <!-- 表单     :rules="searchformRules"-->
                  <el-form
                    :model="searchform"
                
                    label-position="top"
                    ref="searchFormRef"
                    curpagename="stererwe5352"
                  >
              
                    <el-row :gutter="40">
                      <el-col :span="langEnv">
                        <!-- 隶属公司 -->
                        <el-form-item :label="$t(`${langPath}.org_company`)" prop="org_company.value">
                          <el-select 
                            class="qf_select"
                            v-model="searchform.org_company.value"
                            :placeholder="$t(`${langPath}.org_company_placeholder`)"
                            @change="orgCompanyChange"
                          >
                            <el-option
                              :label="item.label"
                              :value="item.value"
                              v-for="item in searchform.org_company.options"
                              :key="item"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="langEnv">
                        <!-- 部门 -->
                        <el-form-item :label="$t(`${langPath}.org_department`)" prop="org_department.value">
                          <el-select 
                            class="qf_select"
                            :disabled="org_department_disabled"
                            v-model="searchform.org_department.value"
                            :placeholder="$t(`${langPath}.org_department_placeholder`)"
                            @change="orgDepartmentChange"
                          >
                            <el-option
                              :label="item.label"
                              :value="item.value"
                              v-for="item in searchform.org_department.options"
                              :key="item"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="langEnv">
                        <!-- 岗位 -->
                        <el-form-item :label="$t(`${langPath}.org_title`)" prop="org_title.value">
                          <el-select
                            class="qf_select"
                            :disabled="org_title_disabled"
                            v-model="searchform.org_title.value"
                            :placeholder="$t(`${langPath}.org_title_placeholder`)"
                          >
                            <el-option
                              :label="item.label"
                              :value="item.value"
                              v-for="item in searchform.org_title.options"
                              :key="item"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    <!-- </el-row>

                    <el-row :gutter="40"> -->
                      <el-col :span="langEnv">
                        <!-- 入职日期 -->
                        <el-form-item :label="$t(`${langPath}.hiredate`)" prop="hiredate.value">
                          <el-date-picker
                            class="qf_date"
                            v-model="searchform.hiredate.value"
                            type="date"
                            :placeholder="$t(`${langPath}.hiredate_placeholder`)"
                            :format="format"
                            :value-format="format"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="langEnv">
                        <!-- 工作性质 -->
                        <el-form-item :label="$t(`${langPath}.job_nature`)" prop="job_nature.value">
                          <el-select
                            class="qf_select"
                            v-model="searchform.job_nature.value"
                            :placeholder="$t(`${langPath}.job_nature_placeholder`)"
                          >
                            <el-option
                              :label="item.label"
                              :value="item.value"
                              v-for="item in searchform.job_nature.options"
                              :key="item"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="langEnv"  style="display: none">
                        <!-- 合同签订公司 -->
                        <el-form-item
                          style="display: none"
                          :label="$t(`${langPath}.contract_company_id`)"
                          prop="contract_company_id.value"
                        >
                          <el-select
                            class="qf_select"
                            v-model="searchform.contract_company_id.value"
                            :placeholder="$t(`${langPath}.contract_company_id_placeholder`)"
                          >
                            <el-option
                              :label="item.label"
                              :value="item.value"
                              v-for="item in searchform.contract_company_id.options"
                              :key="item"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    <!-- </el-row>
                    <el-row :gutter="40" style="display: none">
                      -->
                      <el-col :span="langEnv">
                        <!-- 状态 -->
                        <el-form-item :label="$t(`${langPath}.status`)" prop="status.value">
                          <el-select
                            class="qf_select"
                            v-model="searchform.status.value"
                            :placeholder="$t(`${langPath}.status_placeholder`)"
                          >
                            <el-option
                              :label="item.label"
                              :value="item.value"
                              v-for="item in searchform.status.options"
                              :key="item"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="langEnv">
                        <el-form-item :label="$t(`${langPath}.contract_type`)" prop="contract_type.value">
                          <!-- 合同类型 -->
                          <el-select
                            class="qf_select"
                            v-model="searchform.contract_type.value"
                            :placeholder="$t(`${langPath}.contract_type_placeholder`)"
                          >
                            <el-option
                              :label="item.label"
                              :value="item.value"
                              v-for="item in searchform.contract_type.options"
                              :key="item"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="langEnv">
                        <!-- 合同期限 -->
                        <el-form-item :label="$t(`${langPath}.contract_period`)" prop="contract_period.value">
                          <el-input
                            class="qf_input"
                            :placeholder="$t(`${langPath}.contract_period_placeholder`)"
                            v-model="searchform.contract_period.value"
                            v-number:1="2"
                          />
                        </el-form-item>
                      </el-col>
                    <!-- </el-row>

                    <el-row :gutter="40"> -->
                    
                    
                      <el-col :span="langEnv">
                        <!-- 合同开始日期 -->
                        <el-form-item :label="$t(`${langPath}.contract_start`)" prop="contract_start.value">
                          <el-date-picker
                            class="qf_date"
                            size="default"
                            v-model="searchform.contract_start.value"
                            type="date"
                            :placeholder="$t(`${langPath}.contract_start_placeholder`)"
                            :format="format"
                            :value-format="format"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="langEnv">
                        <el-form-item :label="$t(`${langPath}.contract_end`)" prop="contract_end.value">
                          <!-- 合同结束日期 -->
                          <el-date-picker
                            class="qf_date"
                            v-model="searchform.contract_end.value"
                            type="date"
                            :placeholder="$t(`${langPath}.contract_end_placeholder`)"
                            :format="format"
                            :value-format="format"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="langEnv">
                        <!-- 合同签订日期 -->
                        <el-form-item :label="$t(`${langPath}.contract_date`)" prop="contract_date.value">
                          <el-date-picker
                            class="qf_date"
                            v-model="searchform.contract_date.value"
                            type="date"
                            :placeholder="$t(`${langPath}.contract_date_placeholder`)"
                            :format="format"
                            :value-format="format"
                          />
                        </el-form-item>
                      </el-col>


                    </el-row>
                  </el-form>
                  <!-- 表单 -->
                </div>
              </el-scrollbar>
            </div>
            <div class="modal-footer">
              <!-- 取消 -->
              <el-button type="default" @click="closeModal">{{ $t("merak.reset") }}</el-button>
              <!-- 搜索 -->
              <el-button type="primary" @click="submitForm(searchFormRef)">{{ $t("merak.search") }}</el-button>
              <!-- 保存搜索方案 -->
              <el-button plain type="primary" v-if="searchProp.closePlan" @click="showPlanModal">
                {{ $t("merak.save_search_scheme") }}
              </el-button>
            </div>
          </div>
          <!--  高级搜索弹出框内容-->
        </template>
        <!-- /高级搜索弹出框 插槽-->
      </searchBar>
      <!--到期合同为0不展示 -->
 
      <el-alert type="error" curPageName="1710501907429" class="expiration-reminder" v-if="expirationReminder" :closable="false">
        <div class="expiration-reminder-content">
          <el-icon :size="16" color="#E74C3D"><WarningFilled /></el-icon>
          <div>
            到期提醒: <span class="expiration-reminder-num">{{ expirationReminder }}人</span>合同即将到期
          </div>
          <div>点击查看</div>
        </div>
      </el-alert>

      <!-- 表格组件 -->
      <MerakXTable
        ref="tableRef"
        v-bind="tablePayload"
        :column-type="[{ type: 'handle', width: 90, slot: 'handler' }]"
        :handler-click="handleHanderClick"
        :query-columns="queryColumns"
        :query-data="queryData"
        style="margin-top: 28px"
      >
        <!-- 员工详情插槽 -->
        <template #employee_details="{ row }">
          <el-popover :show-arrow="false" width="auto" placement="right-start" popper-style="min-width: 472px">
            <template #reference>
              <el-button class="employee-button" link style="font-weight: bold">{{ row.employee_name }}</el-button>
            </template>
            <!-- 员工详情信息卡片 -->
            <InfoCard :data="row" />
          </el-popover>
        </template>

        <template #handler="{ row }">
          <div style="display: flex" class="action_wrap" v-auth="{'authArr':auth?.noSigned??{},'key':'add'}">
            <el-button link type="primary" @click="openSignedForm(row)">
              {{ $t("contract_signed.contract_appraisal") }}
            </el-button>
          </div>
        </template>
      </MerakXTable>
    </div>

    <el-drawer modal-class="merak_modal" :size="500" v-model="drawer" title="I am the title" direction="rtl">
      <template #header>
        <!-- 新建合同记录 -->
        <div  class="merak_modal_title">{{ $t("contract_signed.add_new_contract_record") }}</div>
      </template>

      <el-scrollbar height="100%">
        <signedform ref="signedformRef" v-model="drawerSignedForm" @save-success="saveSuccessEvent"></signedform>
      </el-scrollbar>
      <template #footer>
        <el-button type="default" @click="drawer = false">取消</el-button>
        <el-button type="primary" :loading="loadingState.signedFormLoading" @click="submitSignedform()">保存</el-button>
        <!-- <el-button type="success">保存搜索方案</el-button> -->
      </template>
    </el-drawer>
  </div>
</template>
  
<script setup lang="ts" name="noSigned">
import router from "@/routers";
import { ref, reactive, computed, watch, onMounted, nextTick,getCurrentInstance } from "vue";
import { ElButton, ElPopover } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import useDateFormat from "@/hooks/useDateFormat";
import searchBar from "@/components/SearchBar";
import merakColapse from "@/components/merakColapse/index.vue";
import selectedParams from "@/components/SearchBar/components/selectedParams.vue";
import MerakStatCard, { MerakStatCardInstance, MerakStatDataType } from "@/components/MerakStatCard";
import MerakXTable, { MerakXTableInstance, MerakXTableProps } from "@/components/MerakXTable";

import InfoCard from "../signedRecord/components/InfoCard.vue";
import signedform from "../signedRecord/components/signedform.vue";
import useLoading from "@/hooks/useLoading";

import { ResultEnum } from "@/enums/httpEnum";
import {
  Path,
  unSignedGetTableColumns,
  unSignedGetTableData,
  getRouterParams,
  getContractInfo,
  getSearchOptions,
  formartSearchValue,
  authList,
  lang,
  resetUrl
} from "@/api/modules/personalManagementApi/contract";
import { renewal, paramsFromUrlInterFace } from "./index.ts";
import treeNode from "@/views/personalManagement/a-components/oragnizationTree/index.vue";
const auth=reactive(authList);
lang(getCurrentInstance)
// 合同页面翻译 路由前缀
const langPath = ref("contract_signed");
const {proxy}=getCurrentInstance();
const langEnv=proxy.$t('lang')=="ru"?8:6
const tableRef = ref<MerakXTableInstance>();
const signedformRef = ref();
// treeNodeDefault 左侧组织架构默认选中项
const treeNodeDefaultOrgId = ref<number | string>(0);
const loadingState = ref({
  signedFormLoading: false
});
//格式化时间
const { format } = useDateFormat();
//当前节点数据
const treeNodeData = ref<treeNodeDataInterFace>({
  level: 0,
  parent_id: 0,
  org_id: 0
});
//treeNodeData 点击回调
const treeNodeChange = data => {
  treeNodeData.value = { ...treeNodeData.value, ...data };
  treeNodeDefaultOrgId.value = treeNodeData.value.org_id;
  state.statParams = { up: new Date().getTime() ,...treeNodeData.value};
  paramsFromUrl.value={};
  setUrlParams(true); //点击组织架构，同步url参数，更新url
  companyLink(); //联动 高级搜索表单组织架构
};
// settreeNodeData
const settreeNodeData = (level, parent_id, org_id) => {
  console.log(level,parent_id,org_id)
  level=level=='NaN'?0:level;
  parent_id=parent_id=='NaN'?0:parent_id;
  org_id=org_id=='NaN'?0:org_id;
  let obj = {
    level:Number(level??0),
    parent_id:Number(parent_id??0),
    org_id:Number(org_id??0)
  };
  treeNodeData.value = { ...treeNodeData.value, ...obj };
  treeNodeDefaultOrgId.value = treeNodeData.value.org_id;
  setUrlParams()
};
// url搜索参数 会合并到 table搜索参数中
const paramsFromUrl = ref<paramsFromUrlInterFace>({
  job_natur: ""
});

//设置url参数
const setUrlParams = async(isReset) => {
  isReset?await resetUrl():null;
  const newUrl = new URL(window.location.href); 
  newUrl.searchParams.set("org_id", treeNodeDefaultOrgId.value);
  newUrl.searchParams.set("level", treeNodeData.value.level);
  newUrl.searchParams.set("parent_id", treeNodeData.value.parent_id);
  treeNodeDefaultOrgId.value = treeNodeData.value.org_id;
  window.history.pushState({}, "", newUrl.toString());
};
//获取路由参数，修改 treeNode 数据
getRouterParams(router).then(res => {
  const { level, parent_id, org_id, job_nature,contract_end_soon } = res;
  // treeNodeData.value.level = level;
  // treeNodeData.value.parent_id = parent_id;
  // treeNodeData.value.org_id = org_id;
  // treeNodeDefaultOrgId.value = org_id;
  settreeNodeData(level, parent_id, org_id);
  paramsFromUrl.value.job_nature = job_nature;
  if(contract_end_soon){
    paramsFromUrl.value.contract_end_soon = contract_end_soon;
  }
});

//合同即将到期人数
const expirationReminder = ref(0);

// 使用队列 loading 管理初始化页面加载状态
const { queueLoading, queueId } = useLoading();

// 页面配置数据
const state = reactive<{
  filterOptions: Array<any>;
  statValue: string;
  statData: MerakStatDataType[][];
  statParams: Record<string, string>;
}>({
  // 高级搜索方案下拉选项
  filterOptions: [],
  // 统计筛选激活项
  statValue: "",
  // 统计筛选数据
  statData: [],
  // 统计筛选激活后筛选数据
  statParams: {}
});

// 动态计算表格的外部筛选数据
const params = computed(() => ({ ...state.statParams }));

// 表格配置属性
const tablePayload = reactive<MerakXTableProps>({
  // 列设置存储的数据对照值
  columnsByStore: [],
  columnMinWidth: 140,
  // 表格行数据的唯一 key, 跟后端同步
  rowKey: "user_id",
  enabledExport:true,//导出
  // 初始化的外部筛选数据
  params,
  // 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
  // ["multiple", { type: 'handle', width: 200, slot: 'custom_slot_name' | ({ row })=> Component }]
  columnType: ["multiple", "handle"]
  // // 批量操作选项
  // batches: [{ type: "delete", text: "批量删除", color: "red" }],
  // // 操作列选项
  // handles: [{ type: "delete", text: "删除", color: "red" }]
});

// 统计筛选激活触发 table 数据请求
const handleStatChange: MerakStatCardInstance["onChange"] = params => {
  state.statParams = params;
};

/**
 * 表格批量操作事件触发
 * @param type 同 tablePayload.batched 子项的 type
 * @param mode 表格选中的模式  current: 当前页  all: 所有页
 * @param selectedKeys 表格当前页选中模式下选中的行数据 key 的集合, 表格所有页选中模式下未选中的行数据 key 的集合
 */
const handleBatchClick: MerakXTableInstance["batchClick"] = async ({ type, mode, selectedKeys }) => {
  switch (type) {
    case "delete":
      return {
        // 是否刷新表格, 默认 false, 可选参数
        refresh: false,
        // 是否重置表格(分页、排序), 默认 false, 可选参数
        reset: false
      };
    default:
      return;
  }
};

/**
 * 表格操作列事件触发
 * @param type 同 tablePayload.handles 子项的 type
 * @param params 表格操作数据, 可结构关于操作行的数据 { row, rowIndex, rowId }
 */
const handleHanderClick: MerakXTableInstance["handlerClick"] = async ({ type, params }) => {
  switch (type) {
    case "delete":
      alert("delete");
      // 是否刷新表格, 默认 false, 可选参数
      return true;
    case "caht":
      alert("caht");
      // 是否刷新表格, 默认 false, 可选参数
      return true;
    default:
      return;
  }
};

// 获取高级搜索方案
const queryFilterOptions = async data => {
  searchbar.value.getPlanList(data.table_id);
  // 初始化接口需要传入队列 loading 暴露的 id
};

// 获取统计数据
const queryStatData = async () => {
  // 初始化接口需要传入队列 loading 暴露的 id
  return getStatistics(queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      state.statData = Object.values(data).map(item => item);
      if (!!state.statData?.[0]?.[0]) {
        state.statData[0][0].horizontal = true;
      }
    }
  });
};

// 获取表头数据
const queryColumns: MerakXTableInstance["queryColumns"] = async () => {
  // 初始化接口需要传入队列 loading 暴露的 id
  return unSignedGetTableColumns(Path.personnel, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      //获取表头后使用tableid 获取搜索方案
      queryFilterOptions(data);
      // 克隆表头数据作为列设置的对照数据
      tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      return {
        ...data,
        columns: [...data.columns].map(column => {
          switch (column.field) {
            // 扩展插槽悬浮员工姓名展开员工详情卡片
            case "employee_name":
              // 设置最小宽度
              column.width = 180;
              // 固定列
              column.fixed = "left";
              column.slots = { default: "employee_details" };
              return column;
            default:
              return column;
          }
        })
      };
    }
  });
};

/**
 * 获取表格数据
 * @param page 分页参数
 * @param sorts 多重排序参数
 * @param filters 表头筛选参数
 * @param from 外部由 tablePayload.params 传入的自定义参数
 */
const queryData: MerakXTableInstance["queryData"] = async ({ page, sorts, from }) => {
  // 创建请求表格数据的参数
  const params: Record<string, any> = {};
  // 如果有分页数据
  if (!!page) {
    Object.assign(params, { ...page });
  }
  // 如果有排序数据
  if (!!sorts) {
    for (let sort of sorts.values()) {
      console.log(sort);
    }
  }
  // 如果有自定义参数
  if (!!from) {
    for (let key of Object.keys(from)) {
      const item = from[key];
      !!item && (params[key] = item);
    }
  }
  Object.assign(params, treeNodeData.value, paramsFromUrl.value);
  // 初始化接口需要传入队列 loading 暴露的 id
  return unSignedGetTableData(params, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      console.log(data);
      expirationReminder.value = Number(data.dueContract) || 0;
      return data.table_data;
    }
  });
};

// 初始化页面
const init = async () => {
  //   queryFilterOptions();
  // queryStatData();
  //获取路由参数，修改 treeNode 数据
  getRouterParams(router).then(res => {
    const { level, parent_id, org_id, job_nature } = res;
    // treeNodeData.value.level = level;
    // treeNodeData.value.parent_id = parent_id;
    // treeNodeData.value.org_id = org_id;
    // treeNodeDefaultOrgId.value = org_id;
    console.log(level, parent_id, org_id, job_nature);
    settreeNodeData(level, parent_id, org_id);
    paramsFromUrl.value.job_nature = job_nature;
  });
  initSearch();
};

// 高级搜索表单
const searchFormRef = ref<FormInstance>();
const searchform = reactive({
  org_company: {
    label:lang('contract.org_company'), // "隶属公司",   
    value: "",
    type: "select",
    options: []
  },
  org_department: {
    label:lang('contract.org_department'),// "部门",
    value: "",
    type: "select",
    options: []
  },
  org_title: {
    label: lang('contract.org_title'),//"岗位",
    value: "",
    type: "select",
    options: []
  },
  hiredate: {
    label: lang('contract.hiredate'),//"入职日期",
    value: "",
    type: "select",
    options: []
  },

  job_nature: {
    label:lang('contract_signed.job_nature'),// "工作性质",
    value: "",
    type: "select",
    options: []
  },
  contract_company_id: {
    //合同签订公司
    label:lang('contract.contract_company'),// "合同签订公司",
    value: "",
    type: "select",
    options: []
  },
  status: {
    label: lang('contract.status'),//"状态",
    value: "",
    type: "select",
    options: [
      { label: "在职", value: 1 },
      { label: "试用期", value: 2 }
    ]
  },
  contract_type: {
    label:  lang('contract.contract_type'),//"合同类型",
    value: "",
    type: "select",
    options: []
  },
  contract_period: {
    label: lang('contract.contract_period'),//"合同期限",
    value: ""
  },
  contract_start: {
    label:lang('contract.contract_start'), //"合同开始日期",
    value: ""
  },
  contract_end: {
    label: lang('contract.contract_end'),//"合同结束日期",
    value: ""
  },
  contract_date: {
    label: lang('contract.contract_date'),//"合同签订日期",
    value: ""
  }
});

//高级搜索模态
const searchbar = ref();

//触发了快速搜索或者搜索方案
const searchBarPost = params => {
  paramsFromUrl.value={};
  let postParams = { ...params.params, ...{ employee_name_job_no: params.employee_name_job_no } };
  state.statParams = postParams;
};

//点击取消按钮关闭高级搜索模态框
const closeModal = () => {
  searchFormRef.value?.resetFields();
  searchbar.value.modalHide();
  searchbar.value.clear();
  settreeNodeData(0, 0, 0);
  paramsFromUrl.value={};
  state.statParams = { ...searchbar.value.formParams("value") };
};

//打开搜索方案弹出
const showPlanModal = () => {
  searchbar.value.showPlanModal();
  // companyLink();
};

//搜索表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
 
  let treeObj = {};
  if (searchform.org_department.value) {
    //lv2 
    settreeNodeData(2, Number(searchform.org_company.value), Number(searchform.org_department.value));
    console.log(JSON.stringify(treeNodeData));
  } else {
    if (searchform.org_company.value) {
      //lv1 
      settreeNodeData(1, 0, Number(searchform.org_company.value));
    }
  }
  setUrlParams(true); //表单提交联动url
  paramsFromUrl.value={};//点击搜索时候重置来初始化自于URL的参数
  state.statParams = { ...formartSearchValue(searchbar.value.formParams("value")) };
  searchbar.value.clear();

  searchbar.value.modalHide();
 
  
};

//初始化搜索联动
const initSearch = () => {
  getSearchOptions({'auth_name':'noSigned'}).then(res => {
    tablePayload.enabledExport=authList?.noSigned?.export?.show??false
    Object.assign(org_structure, res.orgs);
    console.log(org_structure);
    Object.assign(searchform.org_company.options, res.orgs);
    Object.assign(searchform.status.options, res.status);
    Object.assign(searchform.contract_company_id.options, res.contract_company_id);
    Object.assign(searchform.job_nature.options, res.job_nature);
    Object.assign(searchform.contract_type.options, res.contract_type);

    companyLink();
  });
};
//高级搜索表单联动禁用 true 为禁用
const org_department_disabled = ref(true);
const org_title_disabled = ref(true);
const org_company_readonly = () => {
  let org_company = searchform.org_company.value ?? "";
  let org_department = searchform.org_department.value ?? ""; 
  if (org_company.toString().length == 0) {
    org_title_disabled.value = true;
    org_department_disabled.value = true;
    searchform.org_department.value = "";
    searchform.org_title.value = "";
    return;
  } else {
    org_department_disabled.value = false;
  }

  if (org_department.toString().length == 0) {
    org_title_disabled.value = true;
    searchform.org_title.value = "";
  } else {
    org_title_disabled.value = false;
  }
};

//高级搜表单联动
const companyLink = () => {
  let { level, org_id, parent_id } = treeNodeData.value;
  console.log(level, org_id, parent_id);
  if (!org_id) {
    //说明当前选中的是全部，不做操作
    return;
  }
  if (!level) {
    searchform.org_company.value = Number(parent_id);
    searchform.org_department.value = Number(org_id);
    // setOrgDepartmentOptions(searchform.org_company.value);
    // setOrgTitleOptions(Number(org_id))
  }
  if (level == 1) {
    searchform.org_company.value = Number(org_id);
    // setOrgDepartmentOptions(Number(org_id));
  }
  if (level == 2) {
    searchform.org_company.value = Number(parent_id);
    searchform.org_department.value = Number(org_id);
    // setOrgDepartmentOptions( Number(parent_id));
    // setOrgTitleOptions(Number(org_id))
  }
};

//新增合同表单模态
const drawer = ref<Boolean>(false);
const org_structure = reactive([]);
 
//新增合同表单
const drawerSignedForm = reactive({
  cascader: {
    value: [],
    label: "",
    options: []
  },
  employee_name: {
    value: "",
    label: "",
    options: []
  },
  contract_no: {
    value: "",
    label: lang('contract.contract_number'),//"合同编号"
  },
  contract_type: {
    value: "",
    label:  lang('contract.contract_type'),//"合同类型",
    options: []
  },
  contract_period: {
    value: "",
    label: lang('contract.contract_period'),//"合同期限",
    isShow: true
  },
  contract_start: {
    value: "",
    label: lang('contract.contract_start'),//"合同开始时间"
  },
  contract_end: {
    value: "",
    label:lang('contract.contract_end'),// "合同结束时间"
  },
  contract_company_id: {
    value: "",
    label: lang('contract.contract_company'),// "合同签定公司",
    options: []
  },
  contract_status: {
    value: "",
    label:lang('contract.contract_status'),// "合同状态",
    options: []
  },
  contract_date: {
    value: "",
    label: lang('contract.contract_date'),// "合同签订日期"
  },
  remind: {
    value: "1",
    label: "是否到期提醒"
  },
  last_terminate_reason: {
    value: "",
    label: lang('contract.last_terminate_reason')
  },
  editInfo: {
    name: "",
    title: "",
    isEdit: false,
    minStartDate: ""
  },
  renewal: {
    name: "",
    title: "",
    isRenewal: false,
    minStartDate: ""
  },
  user_id: {
    value: "",
    label: "合同备注"
  },
  user_contract_id: {
    value: ""
  },
  type_id:{
    value: "noSigned",
  }
});

const openSignedForm = row => {
  drawer.value = true;
  console.log(row);
  //
  drawerSignedForm.renewal.isRenewal = true; //表单续签状态
  drawerSignedForm.renewal.name = row.employee_name;
  drawerSignedForm.user_id.value = row.user_id;

  nextTick(() => {
    signedformRef.value.reset().then(res => {
      drawerSignedForm.contract_start.value = dayjs().format("YYYY-MM-DD");
      drawerSignedForm.contract_period.value = '3';//续签(新建) 默认给3年
    });
  });
};
const submitSignedform = () => {
  loadingState.value.signedFormLoading = true;
  if (!signedformRef.value.valid()) {
    loadingState.value.signedFormLoading = false;
  }
};
const saveSuccessEvent = () => {
  drawer.value = false;
  ElMessage({
    message: lang('merak.action_success'),// "保存成功",
    type: "success"
  });
  loadingState.value.signedFormLoading = false;
  tableRef?.value.reloadData();
};
//编辑合同表单
const renewal = row => {
  drawer.value = true;
  console.log(row);
};

// 监听初始化队列 loading 状态
watch(queueLoading, () => {
  if (queueLoading.value) {
    // 页面初始化队列 loading 时不允许 table 自动 loading
    tablePayload.loading = false;
  } else if ("loading" in tablePayload) {
    // 队列 loading 完成后清除 table 受控的 loading 属性
    delete tablePayload.loading;
  }
});

const orgCompanyChange = value => {
  searchform.org_department.value = "";
  searchform.org_title.value = "";
};

const orgDepartmentChange = value => {
  searchform.org_title.value = "";
};

watch(
  () => searchform.org_company.value,
  (n, v) => {
    let options = JSON.parse(JSON.stringify(searchform.org_company.options));

    let index = options.findIndex(item => {
      return item?.value == n;
    });

    searchform.org_department.options = org_structure[index]?.children ?? [];
    org_company_readonly()
    // setOrgDepartmentOptions(searchform.org_company.value);
  }
);
watch(
  () => searchform.org_department.value,
  (n, v) => {
    let options = JSON.parse(JSON.stringify(searchform.org_department.options));

    let index = options.findIndex(item => {
      return item?.value == n;
    });

    searchform.org_title.options = searchform.org_department.options[index]?.children;
    org_company_readonly()
  }
);
watch(
  () => drawer,
  (n, v) => {
    if (!n) {
      signedformRef.value.reset();
    }
  }
);

// 运行初始化
onMounted(() => init());
</script>
  
  <style scoped lang="scss">
@import "./index.scss";
</style>
  